package com.inspur.common.utils.file;

/**
 * @Description
 * @Date 2020/3/4 18:46
 * @auther SunJW
 */

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.DefaultThumbImageConfig;
import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

@Component
public class FastDFSClient {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private DefaultThumbImageConfig defaultThumbImageConfig;

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream (file);
        StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return getResAccessUrl(storePath);
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
//        String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        return storePath.getFullPath();
    }

    /**
     * 下载文件
     * @param fileUrl 文件url
     * @return
     */
    public byte[] download(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }

    /**
     * 删除多个文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFiles(String[] fileUrl) {
        if(fileUrl != null && fileUrl.length > 0){
            for(String url : fileUrl){
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                try {
                    StorePath storePath = StorePath.parseFromUrl(url);
                    storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
                } catch (FdfsUnsupportStorePathException e) {
                    logger.warn(e.getMessage());
                }
            }
        }
    }

    /**
     * 删除多个图片及缩略图
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteImageWithThumbImage(String[] fileUrl){
        if(fileUrl != null && fileUrl.length > 0){
            for(String url : fileUrl){
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                try {
                    //删除源文件
                    StorePath storePath = StorePath.parseFromUrl(url);
                    storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
                    //删除缩略图
                    StorePath thumbImage = StorePath.parseFromUrl(defaultThumbImageConfig.getThumbImagePath(url));
                    storageClient.deleteFile(thumbImage.getGroup(), thumbImage.getPath());
                } catch (Exception e) {
                    logger.warn(e.getMessage());
                }
            }
        }
    }

    /**
     * 查看文件的信息
     *
     * @param fileUrl
     * @return
     */
    public FileInfo getFile(String fileUrl) {
        FileInfo fileInfo = null;
        String groupName = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        logger.info("文件信息入参，groupName:{}，path:{}", groupName, path);
        try {
            fileInfo = storageClient.queryFileInfo(groupName, path);
            logger.info("文件信息:{}", fileInfo.toString());
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return fileInfo;
    }

    /**
     * 获取文件元信息
     *
     * @param fileUrl
     * @return
     */
    public Set<MetaData> getMetadata(String fileUrl) {
        String groupName = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        Set<MetaData> metadata = new HashSet<>();
        try {
            metadata = storageClient.getMetadata(groupName, path);
            logger.info("文件元信息:{}", metadata.toArray());
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return metadata;
    }

    /**
     * 上传图片并且生成缩略图
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadImageAndCrtThumbImage(MultipartFile file) {
        StorePath storePath = null;
        try {
            storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        }catch (Exception e){
            e.printStackTrace();
        }

        return getResAccessUrl(storePath);
    }

}
